package com.guli.order.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean isMatch = antPathMatcher.match("/order/order/orderStatus/**", request.getRequestURI());
        boolean isMatch1 = antPathMatcher.match("/payed/notify", request.getRequestURI());
        if (isMatch || isMatch1){
            return true;
        }
        Object obj =  request.getSession().getAttribute("loginUser");
        String jsonString = JSON.toJSONString(obj);
        MemberRespVo loginUser = JSON.parseObject(jsonString, new TypeReference<MemberRespVo>() {
        });
        if (loginUser != null) {
            //已登录
            threadLocal.set(loginUser);
            return true;
        } else {
            //未登录
            request.getSession().setAttribute("msg", "请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login");
            return false;
        }
    }
}
